import router from "./router"
import cache from '@/utils/cache'
import { useLoginStore } from "@/store/login"

// 路由白名单
const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  // 获取token
  let token = cache.getCache('token')
  // 登录store
  let loginStore = useLoginStore()
  if (token) {
    if (to.path === '/login') {
      next({ path: "/" });
    } else {
      let userInfo = loginStore.userInfo
      if (JSON.stringify(userInfo) != "{}") {
        next()
      } else {
        try {
          // 获取用户信息
          await loginStore.getUserInfo()
          // 获取路由菜单
          await loginStore.getMenusList()
          // 调试路由是否注册成功
          // console.log('当前路由表:', router.getRoutes())
          // 注册动态路由
          loginStore.registerDynamicRoutes()
          next({ ...to, replace: true })

        } catch {
          loginStore.reset()
          next(`/login`);
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login`);
    }
  }
})

